<?php


namespace app\admin\controller;

use app\model\OperationLog as ModelOperationLog;
use app\model\AdminGroup as ModelAdminGroup;
use app\model\AdminInfo as ModelAdminInfo;
use app\model\AdminPassport as ModelAdminPassport;

class Permissions extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 操作日志列表 \n
     * URI : /admin/operation.log.list
     * @param :
     *  name       | type   | null | description
     * ------------|--------|------|-------------
     *  passport   | string | 必填  | 凭证
     *  adminName  | string | 选填  | 管理员名称
     *  gmtStart   | string | 选填  | 开始时间 （例：gmtStart = '2018-05-01 00:00:00';//
     *  gmtEnd     | string | 选填  | 结束时间（例：gmtEnd = '2018-05-30 23:59:59';//）
     *
     *  page       | int    | 必填  | 页码
     *  listRows   | int    | 必填  | 一页的条数
     *
     * @return :
     *  name       | type   | description
     * ------------|--------|-------------
     *  totalPages | string | 总页数
     *  list       | array  | 列表
     *
     * list:
     *  name       | type   | description
     * ------------|--------|-------------
     *  operationId| int    | 编号(id)
     *  adminName  | string | 操作者
     *  ip         | string | 操作日期
     *  content    | string | IP地址
     *  gmtCreate  | string | 操作记录
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function operationLogList(){
        $int_now_page = $this->_getContentParams('page'); // 当前页码
        _toValidate('id', $int_now_page, 10005);
        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        _toValidate('id', $int_list_rows, 10006);

        $str_admin_name = $this->_getContentParams('adminName'); // 管理员名称
        $str_gmt_start = $this->_getContentParams('gmtStart');//开始时间
        $str_gmt_end = $this->_getContentParams('gmtEnd');  //结束时间
        $arr_where = $this->operationLogListWhere($str_admin_name, $str_gmt_start, $str_gmt_end);

        $int_total_rows = ModelOperationLog::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
        $str_field = 'id AS operationId,admin_name AS adminName,ip,content,gmt_create AS gmtCreate';
        $arr_list = ModelOperationLog::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * @param $str_admin_name
     * @param $str_gmt_start
     * @param $str_gmt_end
     * @return array
     */
    public function operationLogListWhere($str_admin_name, $str_gmt_start, $str_gmt_end){
        $arr_where = [];
        if($str_admin_name != ''){
            $arr_where['admin_name'] = $str_admin_name;
        }
        if($str_gmt_start != '' && $str_gmt_end != '') {//时间判断
            _toCompare($str_gmt_start < $str_gmt_end, '===', false, 30003);
            $arr_where['gmt_create'] = ['between' , [$str_gmt_start, $str_gmt_end]];
        }
        return $arr_where;
    }

    /**
     * 管理员名称（操作日志下拉框） \n
     * URI : /admin/operation.name
     * @param :
     *  name     | type   | null | description
     * ----------|--------|------|-------------
     *  -------- | ------ | 无
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  list         | array  | 列表
     *
     * list:
     *  name         | type   | description
     * --------------|--------|-------------
     * adminName     | string | 管理员名称
     *
     */
    public function operationName(){
        $arr_admin_name = ModelOperationLog::getInstance()->toGroup('admin_name AS adminName', 'admin_name');
        _returnData($arr_admin_name);
    }

    /**
     * 部门管理添加 \n
     * URI : /admin/department.add
     * @param :
     *  name     | type   | null | description
     * ----------|--------|------|-------------
     *  roleName | string | 必填  | 部门名称
     *  content  | string | 必填  | 职能描述
     *
     * @return :
     *  name     | type   | description
     * ----------|--------|-------------
     *  -------- | ------ | 无
     *
     */
    public function departmentAdd(){
        $str_role_name = $this->_getContentParams('roleName');//部门名称
        _toCompare(empty($str_role_name), '===', true, 30201);
        $int_role_name_id = ModelAdminGroup::getInstance()->toValue(['role_name' => $str_role_name], 'id');
        _toCompare(($int_role_name_id > 0), '===', true, 30202);
        $str_content = $this->_getContentParams('content');  //职能描述
        _toCompare(empty($str_content), '===', true, 30203);
        $arr_data = [
            'role_name' => $str_role_name,
            'content' => $str_content,
        ];
        ModelAdminGroup::getInstance()->toAdd($arr_data);
        $this->operationLogAdd('部门管理添加');
        _returnData();
    }

    /**
     * 部门管理修改 \n
     * URI : /admin/department.modify
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  departmentId | int    | 必填  | 部门ID
     *  roleName     | string | 必填  | 部门名称
     *  content      | string | 必填  | 职能描述
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  --------     | ------ | 修改完成会将这个部门的成员所在部门全部改成修改后的部门
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function departmentModify(){
        $int_department_id = $this->_getContentParams('departmentId');//部门ID
        _toValidate('id', $int_department_id, 10009);
        $str_role_name = $this->_getContentParams('roleName');//部门名称
        _toCompare(empty($str_role_name), '===', true, 30201);
        $int_id = ModelAdminGroup::getInstance()->toValue(['role_name' => $str_role_name, 'id' => ['NEQ', $int_department_id]], 'id');
        _toCompare(($int_id > 0), '===', true, 30202);
        $str_content = $this->_getContentParams('content');  //职能描述
        _toCompare(empty($str_content), '===', true, 30203);
        $arr_data = [
            'role_name' => $str_role_name,
            'content' => $str_content,
        ];
        $str_name = $this->obtainRoleName($int_department_id);
        ModelAdminInfo::getInstance()->toUpdate(['department' => $str_name], ['department' => $str_role_name]);
        ModelAdminGroup::getInstance()->toUpdate(['id' => $int_department_id], $arr_data);
        $this->operationLogAdd('部门管理修改');
        _returnData();
    }

    /**
     * 获取部门名称
     * @param $int_department_id
     * @return mixed
     */
    private function obtainRoleName($int_department_id){
        return ModelAdminGroup::getInstance()->toValue(['id' => $int_department_id], 'role_name');
    }

    /**
     * 部门管理详情 \n
     * URI : /admin/department.details
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  departmentId | int    | 必填  | 部门ID
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  roleName     | string | 部门名称
     *  content      | string | 职能描述
     *
     */
    public function departmentDetails(){
        $int_department_id = $this->_getContentParams('departmentId');//部门ID
        _toValidate('id', $int_department_id, 10009);
        $arr_data = ModelAdminGroup::getInstance()->toFind(['id' => $int_department_id], 'role_name AS roleName,content');
        _returnData($arr_data);
    }

    /**
     * 部门管理是否启用修改 \n
     * URI : /admin/department.enable
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  departmentId | int    | 必填  | 部门ID
     *  isEnable     | int    | 必填  | 是否启用 1是 0否  （isEnable = 1）
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  ------------ | ------ | 无
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function departmentEnable(){
        $int_department_id = $this->_getContentParams('departmentId');//部门ID
        _toValidate('id', $int_department_id, 10009);
        $int_is_enable = $this->_getContentParams('isEnable');                // 是否启用 1是 0否
        _toCompare(in_array($int_is_enable, [0,1]), '==', false, 30204);

        $str_role_name = $this->obtainRoleName($int_department_id);
        ModelAdminGroup::getInstance()->toUpdate(['id' => $int_department_id], ['is_enable' => $int_is_enable]);
        ModelAdminInfo::getInstance()->toUpdate(['department' => $str_role_name], ['is_enable' => $int_is_enable]);
        $this->operationLogAdd('部门管理是否启用修改');
        _returnData();
    }

    /**
     * 全部部门名称 \n
     * URI : /admin/department.name
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  ------------ | ------ | 无
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  roleName     | string | 部门名称
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function departmentName(){
        $arr_data = ModelAdminGroup::getInstance()->toFieldGroup('role_name AS roleName', 'roleName');
        _returnData(['list' => $arr_data]);
    }

    /**
     * 部门管理删除 \n
     * URI : /admin/department.delete
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  departmentId | int    | 必填  | 部门ID
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  ------------ | ------ | 删除部门时会将该部门的成员全部一并删除
     *
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function departmentDelete(){
        $int_department_id = $this->_getContentParams('departmentId');//部门ID
        _toValidate('id', $int_department_id, 10009);
        $arr_role_name = (string)ModelAdminGroup::getInstance()->toValue(['id' => $int_department_id], 'role_name AS roleName');

        $arr_admin_id = (int)ModelAdminInfo::getInstance()->toFind(['department' => $arr_role_name],'id AS adminId');
        _toCompare(($arr_admin_id['adminId'] == $this->admin_id), '===', true, 30205);

        ModelAdminInfo::getInstance()->toDeleteName(['department' => $arr_role_name]);
        ModelAdminGroup::getInstance()->toDelete(['id' => $int_department_id]);
        $this->operationLogAdd('部门管理删除');
        _returnData();
    }

    /**
     * 部门管理列表 \n
     * URI : /admin/department.list
     * @param :
     *  name       | type   | null | description
     * ------------|--------|------|-------------
     *  passport   | string | 必填  | 凭证
     *  order      | string | 必填  | 排序(以添加时间正倒序) 不填默认正序  必填倒序  order='desc'为倒序
     *
     *  page       | int    | 必填  | 页码
     *  listRows   | int    | 必填  | 一页的条数
     *
     * @return :
     *  name       | type   | description
     * ------------|--------|-------------
     *  totalPages | string | 总页数
     *  list       | array  | 列表
     *
     * list:
     *  name       | type   | description
     * ------------|--------|-------------
     *  groupId    | int    | 部门ID
     *  roleName   | string | 部门名称
     *  content    | string | 职能描述
     *  adminNum   | int    | 成员数量
     *  isEnable   | int    | 是否启用   1是 0否
     *  gmtCreate  | string | 添加时间
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function departmentList(){
        $int_now_page = $this->_getContentParams('page'); // 当前页码
        _toValidate('id', $int_now_page, 10005);
        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        _toValidate('id', $int_list_rows, 10006);
        $str_order = $this->_getContentParams('order'); // 添加时间排序
        $str_order = $this->listOrder('gmt_create', $str_order);

        $arr_where = [];
        $int_total_rows = ModelAdminGroup::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
        $str_field = 'id AS groupId,role_name AS roleName,content,is_enable AS isEnable,gmt_create AS gmtCreate';
        $arr_list = ModelAdminGroup::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, $str_order);
        $arr_list = $this->departmentListModify($arr_list);
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * @param $arr_list
     * @return mixed
     */
    public function departmentListModify($arr_list){
        foreach($arr_list as &$value){
            $value['adminNum'] = (int)ModelAdminInfo::getInstance()->toCount(['department' => $value['roleName']]);
        }
        return $arr_list;
    }

    /**
     * 成员管理添加 \n
     * URI : /admin/admin.add
     * @param :
     *  name            | type   | null | description
     * -----------------|--------|------|-------------
     *  adminName       | string | 必填  | 成员名称
     *  loginAccount    | string | 必填  | 成员账号
     *  adminEmail      | string | 必填  | 邮箱地址
     *  department      | string | 必填  | 所属部门  接口：/admin/department.name
     *  loginPassword   | string | 必填  | 登录密码
     *  note            | string | 选填  | 备注信息
     *
     * @return :
     *  name     | type   | description
     * ----------|--------|-------------
     *  -------- | ------ | 无
     *
     */
    public function adminAdd(){
        $str_admin_name = $this->_getContentParams('adminName');//成员名称
        _toCompare(empty($str_admin_name), '===', true, 30207);
        $str_login_account = $this->_getContentParams('loginAccount');//成员账号
        _toCompare(empty($str_login_account), '===', true, 30208);
        $int_login_id = ModelAdminInfo::getInstance()->toValue(['login_account' => $str_login_account], 'id');
        _toCompare(($int_login_id > 0), '===', true, 30209);
        $str_admin_email = $this->_getContentParams('adminEmail');//邮箱地址
        _toCompare(empty($str_admin_email), '===', true, 30210);
        $str_department = $this->_getContentParams('department');//所属部门
        _toCompare(empty($str_department), '===', true, 30211);
        $str_login_password = $this->_getContentParams('loginPassword');//登录密码
        _toValidate('login_pwd', $str_login_password, 10819);
        $str_pwd_key = $this->_getRandomString(6);
        $str_login_password = passwordEncryption($str_login_password, $str_pwd_key);
        $str_note = $this->_getContentParams('note');//备注信息

        $arr_data = [
            'admin_name' => $str_admin_name,
            'login_account' => $str_login_account,
            'admin_email' => $str_admin_email,
            'department' => $str_department,
            'password' => $str_login_password,
            'pwd_key' => $str_pwd_key,
            'note' => $str_note,
        ];
        ModelAdminInfo::getInstance()->toAdd($arr_data);
        $this->operationLogAdd('成员管理添加');
        _returnData();
    }

    /**
     * 成员管理是否启用修改 \n
     * URI : /admin/admin.enable
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  adminId      | int    | 必填  | 成员ID
     *  isEnable     | int    | 必填  | 是否启用 1是 0否  （isEnable = 1）
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  ------------ | ------ | 无
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function adminEnable(){
        $int_admin_id = $this->_getContentParams('adminId');//成员ID
        _toValidate('id', $int_admin_id, 10009);
        $int_is_enable = $this->_getContentParams('isEnable');                // 是否启用 1是 0否
        _toCompare(in_array($int_is_enable, [0,1]), '==', false, 30204);
        ModelAdminInfo::getInstance()->toUpdate(['id' => $int_admin_id], ['is_enable' => $int_is_enable]);
        $this->operationLogAdd('成员管理是否启用修改');
        _returnData();
    }

    /**
     * 成员管理删除 \n
     * URI : /admin/admin.delete
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  adminId      | int    | 必填  | 成员ID
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  ------------ | ------ | 无
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function adminDelete(){
        $int_admin_id = $this->_getContentParams('adminId');//成员ID

        _toValidate('id', $int_admin_id, 10009);
        _toCompare($int_admin_id, '==', $this->admin_id, 30206);
        ModelAdminInfo::getInstance()->toDelete(['id' => $int_admin_id]);
        $this->operationLogAdd('成员管理删除');
        _returnData();
    }

    /**
     * 成员管理详情 \n
     * URI : /admin/admin.management.details
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  adminId      | int    | 必填  | 成员ID
     *
     * @return :
     *  name         | type   | description
     * --------------|--------|-------------
     *  adminName    | string | 成员名称
     *  department   | string | 部门名称
     *  loginAccount | string | 登录账号
     *  loginPassword| string | 登录密码
     *  loginPasswordVice     | string | 确认密码
     *  adminEmail   | string | 邮箱
     *  note         | string | 备注
     *
     */
    public function adminDetails(){
        $int_admin_id = $this->_getContentParams('adminId');//成员ID
        _toValidate('id', $int_admin_id, 10009);
        $arr_data = ModelAdminInfo::getInstance()->toFind(['id' => $int_admin_id], 'admin_name AS adminName,department,login_account AS loginAccount,admin_email AS adminEmail,note');
        _returnData($arr_data);
    }

    /**
     * 成员管理修改 \n
     * URI : /admin/admin.management.modify
     * @param :
     *  name            | type   | null | description
     * -----------------|--------|------|-------------
     *  adminId         | string | 必填  | 成员ID
     *  adminName       | string | 必填  | 成员名称
     *  loginAccount    | string | 必填  | 成员账号
     *  adminEmail      | string | 必填  | 邮箱地址
     *  department      | string | 必填  | 所属部门  接口：/admin/department.name
     *  loginPassword   | string | 必填  | 登录密码 不填不修改
     *  note            | string | 选填  | 备注信息
     *
     * @return :
     *  name     | type   | description
     * ----------|--------|-------------
     *  -------- | ------ | 修改之后用户的权限要重新勾选
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function adminModify(){
        $int_admin_id = $this->_getContentParams('adminId');//成员ID
        _toValidate('id', $int_admin_id, 10009);
        $str_admin_name = $this->_getContentParams('adminName');//成员名称
        _toCompare(empty($str_admin_name), '===', true, 30207);
        $str_login_account = $this->_getContentParams('loginAccount');//成员账号
        _toCompare(empty($str_login_account), '===', true, 30208);
        $int_login_id = (int)ModelAdminInfo::getInstance()->toValue(['login_account' => $str_login_account, 'id' => ['NEQ', $this->admin_id]], 'id');
        _toCompare(($int_login_id > 0), '===', true, 30209);
        $str_admin_email = $this->_getContentParams('adminEmail');//邮箱地址
        _toCompare(empty($str_admin_email), '===', true, 30210);
        $str_department = $this->_getContentParams('department');//所属部门
        _toCompare(empty($str_department), '===', true, 30211);
        $str_login_password = $this->_getContentParams('loginPassword');//登录密码
        $str_note = $this->_getContentParams('note');//备注信息
        if($str_login_password != ''){
            _toValidate('login_pwd', $str_login_password, 10819);
            $str_pwd_key = $this->_getRandomString(6);
            $str_login_password = passwordEncryption($str_login_password, $str_pwd_key);
        }
        $arr_data = [
            'admin_name' => $str_admin_name,
            'login_account' => $str_login_account,
            'admin_email' => $str_admin_email,
            'department' => $str_department,
            'note' => $str_note,
            'department'=> $str_department,
        ];
        if($str_login_password != ''){
            $arr_data['pwd_key'] = $str_pwd_key;
            $arr_data['password'] = $str_login_password;
        }
        ModelAdminInfo::getInstance()->toUpdate(['id' => $int_admin_id], $arr_data);
        $this->operationLogAdd('成员管理修改');
        _returnData();
    }

    /**
     * 成员管理列表 \n
     * URI : /admin/admin.list
     * @param :
     *  name       | type   | null | description
     * ------------|--------|------|-------------
     *  passport   | string | 必填  | 凭证
     *  order      | string | 必填  | 排序(以添加时间正倒序) 不填默认正序 必为倒序  order='desc'为倒序
     *  adminName  | string | 选填  | 用户名称（模糊查询）
     *  department | string | 选填  | 部门名称（模糊查询）
     *
     *  page       | int    | 必填  | 页码
     *  listRows   | int    | 必填  | 一页的条数
     *
     * @return :
     *  name       | type   | description
     * ------------|--------|-------------
     *  totalPages | string | 总页数
     *  list       | array  | 列表
     *
     * list:
     *  name        | type   | description
     * -------------|--------|-------------
     *  adminId     | int    | 成员ID
     *  loginAccount| string | 用户名称
     *  adminEmail  | string | 邮箱
     *  adminName   | string | 姓名
     *  department  | string | 部门名称
     *  isEnable    | int    | 是否启用   1是 0否
     *  gmtCreate   | string | 添加时间
     *  lastTime    | string | 最后一次登录
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminList(){
        $int_now_page = $this->_getContentParams('page'); // 当前页码
        _toValidate('id', $int_now_page, 10005);
        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        _toValidate('id', $int_list_rows, 10006);
        $str_admin_name = $this->_getContentParams('adminName'); // 姓名
        $str_department = $this->_getContentParams('department'); // 所属部门

        $str_order = $this->_getContentParams('order'); // 添加时间排序
        $str_order = $this->listOrder('gmt_create', $str_order);
        $arr_where = $this->adminListWhere($str_admin_name, $str_department);
        $int_total_rows = ModelAdminInfo::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
        $str_field = 'id AS adminId,admin_name AS adminName,login_account AS loginAccount,admin_email AS adminEmail,department,is_enable AS isEnable,gmt_create AS gmtCreate';
        $arr_list = ModelAdminInfo::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, $str_order);
        $arr_list = $this->adminListModify($arr_list);
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * @param $str_admin_name
     * @param $str_department
     * @return array
     */
    public function adminListWhere($str_admin_name, $str_department){
        $arr_where = [];
        if($str_admin_name != ''){
            $arr_where['admin_name'] = ['like' , "%$str_admin_name%"];
        }
        if($str_department != ''){
            $arr_where['department'] = $str_department;
        }
        return $arr_where;
    }

    /**
     * @param $arr_list
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminListModify($arr_list){
        foreach($arr_list as &$value){
           $str_last_time = ModelAdminPassport::getInstance()->toLimit(['admin_id' => $value['adminId']]);
            if(!empty($str_last_time) == true){
                $value['lastTime'] = $str_last_time[0]['gmtCreate'];
            }else{
                $value['lastTime'] = '暂无登录';
            }
        }
        return $arr_list;
    }

}
